<?php
namespace app\index\controller;

use app\index\model\Member;
use think\Controller;
use think\Request;
use think\Session;

class Index extends Controller
{
    /**
     * 登录验证
     * Index constructor.
     * @param Request $request
     */
    public function __construct(Request $request)
    {
        parent::__construct($request);
        if (Request::instance()->server('REDIRECT_URL') !== '/index') {
            $this->checkLogin();
        }
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        if (Session::get('loginStatus') === true) {
            $this->redirect('/center');
        }
        return $this->fetch('Index/index');
    }

    /**
     * 登录验证
     */
    public function login()
    {
        $this->checkLogin();
        //获取POST数据
        $post = Request::instance()->post();
        //使用验证器验证
        $result = $this->validate($post, 'Member.login');
        if ($result !== true) {
            $this->error($result);
        }
        $plate = $post['plate'];
        $password = $post['password'];
        //获取会员信息
        $member = $this->memberAuth($plate, $password);
        if ($member) {
            Session::set('loginStatus', true);
            $this->success('登录成功');
        } else {
            $this->error('车牌或密码错误');
        }
    }

    /**
     * 验证会员信息
     * @param $plate    $车牌
     * @param $password $密码
     * @return bool
     */
    public function memberAuth($plate, $password)
    {
        $member = null;
        $password = strtoupper(md5($password));
        try {
            $member = Member::where('PlateNo', $plate)
                ->where('Password', $password)
                ->alias('m')
                ->join('card c', 'c.ID = m.CardID')
                ->field('CardID,m.ID')
                ->find();
        } catch (\Exception $e) {
            $this->error('系统错误，请稍后再试');
        }
        if ($member === null) {
            return false;
        } else {
            Session::set('cardID', $member['CardID']);
            Session::set('ID', $member['ID']);
            return true;
        }
    }

    /**
     * 检查登录状态
     * @return bool
     */
    public function checkLogin()
    {
        if (Session::get('loginStatus') !== true) {
            if (!Request::instance()->isAjax()) {
                $this->redirect('/index');
            }
        }
    }
}
